/**
 * 
 */
package com.shy.task.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.quartz.TriggerUtils;
import org.quartz.impl.triggers.CronTriggerImpl;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.shy.base.controller.AbsController;
import com.shy.base.util.BeanUtil;
import com.shy.base.vo.AppConstants;
import com.shy.base.vo.EasyuiPagerVo;
import com.shy.base.vo.PagerFilter;
import com.shy.task.entity.TaskEntity;
import com.shy.task.service.TaskEntityService;

/**
 * <p>Title:TaskEntityController </p>
 * <p>Description: 任务信息 controller层</p>
 * <p>Company:shy </p> 
 * @author H2013788
 * @date 2019年09月21日
 */
@Controller
@RequestMapping("taskEntity")
public class QuartzTaskController extends AbsController {
	
	/**
     * log
     */
	private Logger logger = LogManager.getLogger(this.getClass());

	/**
	 * service层
	 */
    @Resource
    private TaskEntityService taskEntityService;

	/**
	 * 加载页面
	 * @return
	 * @author H2013788
	 * @date 2019年09月21日
	 */
	@RequestMapping("page")
	public String loadPage() {
		return "portal/task_list";
	}
	
	/**
	 * 加载数据
	 * 
	 * @author H2013788
	 * @date 2019年09月21日
	 */
	@RequestMapping("data")
	public void loadData(TaskEntity taskEntity, Integer page, Integer rows, HttpServletResponse response) {
		PagerFilter pagerFilter = getPageable(rows == null ? 15L : rows);
        pagerFilter.setPagePer(null == page ? 1 : page);
        //String[] likes = { "filed1", "filed2" }; 
        //Map<String, String[]> filterMap = new HashMap<>();
        //filterMap.put(AppConstants.LIKE_TYPES, likes);
        pagerFilter = taskEntityService.listByPager(taskEntity, null, pagerFilter);
        //输出json
        writeResponse(new StringBuffer(gsonDateTime.toJson(new EasyuiPagerVo(pagerFilter))), response);
	}
	
	/**
	 * 编辑
	 * 
	 * @author H2013788
	 * @date 2019年09月21日
	 */
	@RequestMapping("edit")
	public void eidt(Integer id, HttpServletResponse response) {
		if (null != id) {
			TaskEntity taskEntity = taskEntityService.getById(id);
            //输出json
            writeResponse(new StringBuffer(gsonDateTime.toJson(taskEntity)), response);
        } else {
            respEasyuiErrorResult(AppConstants.configMap.get(AppConstants.GET_OBJECT_NULL), response);
        }
	} 
	
	
	/**
	 * 保存
	 * 
	 * @author H2013788
	 * @date 2019年09月21日
	 */
	@RequestMapping("save")
	public void save(TaskEntity taskEntity, HttpServletResponse response) {
		if (null == taskEntity) {
            respEasyuiErrorResult(AppConstants.configMap.get(AppConstants.REQUEST_PARAM_NULL), response);
        } else {
            try {
                if (null != taskEntity.getId()) {
                	//编辑
                	TaskEntity old = taskEntityService.getById(taskEntity.getId());
                    BeanUtil.merge(old, taskEntity);
                    taskEntityService.updateJob(old);
                } else {
                	//默认状态为正常启动
                	taskEntity.setStatus(1);
                	taskEntityService.addJob(taskEntity);
                }
				respEasyuiSuccessResult(AppConstants.configMap.get(AppConstants.SAVE_SUCCESS), response);
            } catch (Exception e) {
                e.printStackTrace();
                respEasyuiErrorResult(AppConstants.configMap.get(AppConstants.SAVE_ERROR), response);
                logger.error(AppConstants.configMap.get(AppConstants.SAVE_ERROR) + e);
            }
        }
	}
	
	
	/**
	 * 刪除数据
	 * 
	 * @author H2013788
	 * @date 2019年09月21日
	 */
	@RequestMapping("delete")
	public void delete(Integer id, HttpServletResponse response) {
		try {
            if (null != id) {
            	taskEntityService.deleteJob(id);
                respEasyuiSuccessResult(AppConstants.configMap.get(AppConstants.OPERATE_SUCCESS), response);
            } else {
                respEasyuiErrorResult(AppConstants.configMap.get(AppConstants.REQUEST_PARAM_NULL), response);
            }
        } catch (Exception e) {
            e.printStackTrace();
            respEasyuiErrorResult(AppConstants.configMap.get(AppConstants.OPERATE_ERROR), response);
            logger.error(AppConstants.configMap.get(AppConstants.DELETE_ERROR) + e);
        }
	}
	
	
	/**
	 * 冻结/启动任务
	 * 
	 * @author H2013788
	 * @date 2019年09月21日
	 */
	@RequestMapping("updateStatus")
	public void updateStatus(Integer id, Integer status, HttpServletResponse response) {
		try {
            if (null != id) {
            	if(status == 1) {
            		taskEntityService.resumeQuartzJob(id);
            	}else {
            		taskEntityService.pauseQuartzJob(id);
            	}
                respEasyuiSuccessResult(AppConstants.configMap.get(AppConstants.OPERATE_SUCCESS), response);
            } else {
                respEasyuiErrorResult(AppConstants.configMap.get(AppConstants.REQUEST_PARAM_NULL), response);
            }
        } catch (Exception e) {
            e.printStackTrace();
            respEasyuiErrorResult(AppConstants.configMap.get(AppConstants.OPERATE_ERROR), response);
            logger.error(AppConstants.configMap.get(AppConstants.OPERATE_ERROR) + e);
        }
	}
	
	
	
	/**
	 * cron表达式生成页
	 */
	@RequestMapping("cron")
	public String quartzCronCreate(){
		return "portal/quartz_cron";
	}
	
	
	/**
     * 根据Cron表达式获取任务最近 几次的执行时间
     * @param cron  cron表达式
     * @param count 次数
     * @return
     */
	@ResponseBody
    @RequestMapping("cronTest")
    public List<String> getCronList(String CronExpression, HttpServletRequest request) throws Exception{
        try {
			List<String> list = new ArrayList<String>();
			CronTriggerImpl cronTriggerImpl = new CronTriggerImpl();
			cronTriggerImpl.setCronExpression(CronExpression);
			// 这个是重点，一行代码搞定
			List<Date> dates = TriggerUtils.computeFireTimes(cronTriggerImpl, null, 7);
			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			for (Date date : dates) {
				list.add(dateFormat.format(date));
			}
			return list;
		} catch (ParseException e) {
			e.printStackTrace();
			throw e;
		}
    }
	
	
	
	/**
	 * 立即執行一次
	 * @author H2013788
	 * @date 2019年9月24日
	 */
	@RequestMapping("run")
	public void runNow(Integer id) {
		try {
			if (null != id) {
				taskEntityService.immediateExecuteJob(id);
				respEasyuiSuccessResult(AppConstants.configMap.get(AppConstants.OPERATE_SUCCESS), response);
			} else {
				respEasyuiErrorResult(AppConstants.configMap.get(AppConstants.REQUEST_PARAM_NULL), response);
			}
		} catch (Exception e) {
			 e.printStackTrace();
			 respEasyuiErrorResult(AppConstants.configMap.get(AppConstants.OPERATE_ERROR), response);
			 logger.error(AppConstants.configMap.get(AppConstants.OPERATE_ERROR) + e);
		}
	}
	
	
}
